#!/usr/bin/env python
"""
qnimbus-qualysguard-session-python: Requests a scan via session based authentication in QualysGuard, and prints the scan results. Licensed under GNU GPL v3 (http://www.gnu.org/copyleft/gpl.html). Code hosted at qnimbus-qualysguard repository (qnimbus-qualysguard.googlecode.com).
"""
import subprocess
# Set parameters for HTTPS request.
username = 'your_QualysGuard_username'
password = 'your_QualysGuard_password'
# The QualysGuard API server URL depends where your account is located. 
# E.g.: 'qualys.eu' for EU.
qualys_api_server = 'qualys.com'
# Authenticate to QualysGaurd via session based authentication.
# Set curl arguments.
args = [
    'curl',
    '-H', 'X-Requested-With: Qnimbus demo',
    '-D', 'headers',
    '-d', 'action=login&username=%s&password=%s' % (username, password),
    'https://qualysapi.%s/api/2.0/fo/session/' % (qualys_api_server),
]
output = subprocess.check_output(args).decode("utf-8")
# Set authentication cookie.
cookie=''
infile = open("headers", "r")
for line in infile:
    if re.search('^Set-Cookie', line):
        cookie = line[line.find(':') + 2:-2]
# Request a list of scans 
args = [
    'curl',
    '-H', 'X-Requested-With: Qnimbus demo',
    '-D', 'headers.1',
    '-b', cookie,
    'https://qualysapi.qualys.com/api/2.0/fo/scan/?action=list&echo_request=1&show_ags=1&show_op=1',
]
xml_output = subprocess.check_output(args).decode("utf-8")
# Python 3.x command commented out below.
#print(xml_output)
print xml_output